<?php
declare (strict_types = 1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use EasyWeChat\Factory;
use app\model\JdHistory;
use app\model\JdUser;
use app\model\JdBeanRecord;

class CheckCookie extends Command
{
    protected $app;
    protected function configure()
    {
        // 指令配置
        $this->setName('app\command\checkcookie')
            ->addArgument('test', Argument::OPTIONAL, "for test notify")
            ->addArgument('uid', Argument::OPTIONAL, "for test notify userid, default first user")
            ->setDescription('the app\command\checkcookie command');
    }

    protected function execute(Input $input, Output $output)
    {
        $config = config('wechat');
        $this->app = Factory::officialAccount($config);
        
        $test = $input->getArgument('test');
        if($test) {
            $uid = $input->getArgument('uid');
            if($uid) {
                $user = JdUser::find($uid);
            } else {
                $user = JdUser::where('id', '>', 0)->find();
            }
            if($user) {
                $this->notifyCookieExpired($user);
                $output->writeln("测试发送通知成功：" . json_encode($user));
            } else {
                $output->writeln("测试发送通知失败");
            }
            
            return;
        }
       
        $users = JdUser::select();

        foreach ($users as $key => $value) {
            if(!$value->cookie)
                continue;
            $this->getTotalBean($value, $output);
        }
    }

    protected function getTotalBean(JdUser $user, Output $output) {
        $headers = [
            'User-Agent: jdltapp;iPhone;3.1.0;14.4;network/wifi;hasUPPay/0;pushNoticeIsOpen/0;lang/zh_CN;model/iPhone8,4;addressid/1477231693;hasOCPay/0;appBuild/1017;supportBestPay/0;pv/21.15;apprpd/MyJD_Main;ref/https%3A%2F%2Fgold.jd.com%2F%3Flng%3D0.000000%26lat%3D0.000000%26sid%3D4584eb84dc00141b0d58e000583a338w%26un_area%3D19_1607_3155_62114;psq/0;ads/;psn/2c822e59db319590266cc83b78c4a943783d0077|46;jdv/0|;adk/;app_device/IOS;pap/JA2020_3112531|3.1.0|IOS 14.4;Mozilla/5.0 (iPhone; CPU iPhone OS 14_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148;supportJDSHWK/1',
            'Accept: application/json,text/plain, */*',
            'Content-Type: application/x-www-form-urlencoded',
            'Accept-Encoding: gzip, deflate, br',
            'Accept-Language: zh-cn',
            'Connection: keep-alive',
            'Referer: https://wqs.jd.com/my/jingdou/my.shtml?sceneval=2'
        ];
        try {
            $response = $this->curl_post('https://wq.jd.com/user/info/QueryJDUserInfo?sceneval=2', 
                [], 
                $user->cookie,
                $headers
            );
            $data = json_decode($response);
            if($data->retcode == 0) {
                $user->nickname = $data->base->nickname;
                $user->mobile = $data->base->mobile;
                $user->pt_pin = $data->base->curPin;
                $user->bean_total = $data->base->jdNum;
                $user->save();
                $output->writeln("获取用户总京豆成功：{$user->pt_pin} 总京豆：{$user->bean_total}");
                // $this->notifyBeanTotal($user);
            }

            if($data->retcode == 13) {
                if($user->expired)
                    return;
                $user->expired = 1;
                $user->expired_time = date('Y-m-d H:i:s');
                $user->save();
                $output->writeln("用户Cookie过期：{$user->pt_pin} {$user->mobile}");
                $this->notifyCookieExpired($user);
            } else {
                if($user->expired && $data && $data->retcode == 0) {
                    $user->expired = 0;
                    $user->save();
                }
            }
            
        } catch (\Throwable $th) {
            //throw $th;
            $output->writeln("获取用户总京豆出错：{$user->id} {$user->pt_pin} {$th}");
        }
       
        // $output->writeln('QueryJDUserInfo body = ' . $response);
        // {
        //     "base" : {
        //        "TipUrl" : "http://wqs.jd.com/my/accountv2.shtml?sceneid=11110&state=0&rurl=https://wqs.jd.com/my/jingdou/my.shtml?sceneval=2",
        //        "accountType" : 0,
        //        "curPin" : "153919351_m",
        //        "headImageUrl" : "",
        //        "isJTH" : "0",
        //        "jdNum" : 1230,
        //        "jvalue" : 5792,
        //        "levelName" : "银牌用户",
        //        "mobile" : "138*****667",
        //        "nickname" : "153919351",
        //        "userLevel" : 61
        //     },
        //     "definePin" : 0,
        //     "isHitArea" : 0,
        //     "isHomeWhite" : 0,
        //     "isLongPwdActive" : 0,
        //     "isPlusVip" : false,
        //     "isRealNameAuth" : true,
        //     "isShortPwdActive" : 1,
        //     "msg" : "success.",
        //     "orderFlag" : 1,
        //     "retcode" : 0,
        //     "userFlag" : 1
        //  }
        return json_decode($response);
    }

    public function notifyCookieExpired(JdUser $user){
        try {
            $config = config('wechat');
            $sendResult = $this->app->template_message->send([
                'touser' => $user->openid,
                'template_id' => $config['template_ids']['cookie_expired'],
                'url' => "https://jd.0xaa.cn/index/data?id={$user->id}",
                 'data' => [
                    'Account' => "{$user->pt_pin} ({$user->nickname} {$user->mobile})"
                ]
            ]);
            return $sendResult;
        } catch (\Throwable $th) {
            throw $th;
            return false;
        }
    }

    public function notifyBeanTotal(JdUser $user){
        try {
            $config = config('wechat');
            $this->app->template_message->send([
                'touser' => $user->openid,
                'template_id' => $config['template_ids']['total_bean'],
                'url' => "https://jd.0xaa.cn/index/data?id={$user->id}",
                 'data' => [
                    'Account' => "{$user->pt_pin} ({$user->nickname} {$user->mobile})",
                    'Amount' => "{$user->bean_total}"
                ]
            ]);
        } catch (\Throwable $th) {
            //throw $th;
        }
    }

    function curl_post($url , $data=array(), $cookie,  $headers, $enableGzip = true){

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        // POST数据
        curl_setopt($ch, CURLOPT_POST, 1);
        // 把post的变量加上
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        
        curl_setopt($ch, CURLOPT_COOKIE, $cookie);
        //至关重要，CURLINFO_HEADER_OUT选项可以拿到请求头信息
        curl_setopt($ch, CURLINFO_HEADER_OUT, TRUE);
       
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_TIMEOUT, 15); //timeout in seconds
        if($enableGzip) {
            curl_setopt($ch,CURLOPT_ENCODING , "gzip");
        }
        
        $output = curl_exec($ch);
        //通过curl_getinfo()可以得到请求头的信息
        // $responseHeader=curl_getinfo($ch);
        // echo json_encode($responseHeader);
        curl_close($ch);
        return $output;

    }
}
